package com.smasher.domain.activity

import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.smasher.core.io.FileUtil
import com.smasher.domain.entity.BeanDomain
import com.smasher.domain.model.DomainViewModel
import com.smasher.widget.base.BaseActivity
import kotlinx.coroutines.launch
import java.nio.charset.StandardCharsets

/**
 * @author HXZ_Android
 */
abstract class LoadFirstActivity : BaseActivity() {

    protected val domains: MutableList<BeanDomain> = ArrayList()
    protected val domainViewModel by viewModels<DomainViewModel>()

    protected fun loadFromJSON() {

        lifecycleScope.launch {
            val domains = try {
                val bytes = FileUtil.loadAsset(baseContext, configFileName())
                val gson = GsonBuilder().create()
                val type = object : TypeToken<List<BeanDomain>>() {}.type
                gson.fromJson(String(bytes, StandardCharsets.UTF_8), type)
            } catch (e: Exception) {
                emptyList<BeanDomain>()
            }
            saveDomains(domains)
        }
    }

    private fun saveDomains(list: List<BeanDomain>) {
        domainViewModel.saveList(list)
    }

    protected fun saveDomain(domainCurrent: BeanDomain, callback: (Boolean) -> Unit) {
        domainViewModel.saveSingle(domainCurrent, callback)
    }

    protected abstract fun configFileName(): String

    protected abstract fun loadDomainList()

    companion object {
        const val TAG = "LOAD_FIRST"
    }
}